package com.controller;

import com.entity.Result;
import com.entity.ZuoyetijiaoEntity;
import com.service.ZuoyetijiaoService;
import com.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ConfigEntity;
import com.entity.EIException;
import com.service.ConfigService;
import com.utils.R;
import com.service.ZuoyebuzhiService;
import com.entity.ZuoyebuzhiEntity;

/**
 * 上传文件映射表
 */
@Slf4j
@RestController
@RequestMapping("file")
public class FileController{
	@Autowired
	private ConfigService configService;
	/**
	 * 基于阿里云OSS存储的实现上传功能
	 */
	@Autowired
	private AliyunOSSOperator aliyunOSSOperator;

	@Autowired
	private ZuoyetijiaoService zuoyetijiaoService; // 注意：MyBatis-Plus 推荐使用 Service 而不是 Dao
	@Autowired
	private ZuoyebuzhiService zuoyebuzhiService;

	@PostMapping("/upload")
	public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
		log.info("文件上传：{}",file.getOriginalFilename());
		//将文件交给OSS管理  file.getBytes()获取到文件的字节数组
		String url = aliyunOSSOperator.upload(file.getBytes(),file.getOriginalFilename());
		log.info("文件上传完成，返回访问路径url：{}",url);
		return Result.success(url);
	}

	/**
	 * 下载文件
	 */

	@IgnoreAuth
	@GetMapping("/download")
	public ResponseEntity<byte[]> download(@RequestParam String fileName) {
		try {
			byte[] content = aliyunOSSOperator.download(fileName); // fileName 是 OSS 上的 objectName，如 2025/06/xxx.png

			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.setContentDispositionFormData("attachment", fileName.substring(fileName.lastIndexOf("/") + 1));

			return new ResponseEntity<>(content, headers, HttpStatus.OK);
		} catch (Exception e) {
			log.error("文件下载失败", e);
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

}
